package com.pmgames.store.data
{
	import com.pmgames.store.components.TextComponent;
	import com.pmgames.store.events.JavaFlexBoundaryConditionEvent;
	import com.pmgames.store.events.JavaFlexGameOverEvent;
	
	import flash.events.EventDispatcher;
	
	public class RelationsToGuess extends EventDispatcher
	{
		private var relationList:RelationArrayCollection;
		private var relationsToOpen:int;//usedWords
		
		public function RelationsToGuess(source:Array = null):void
		{
			if(source != null)
			{
				relationList = new RelationArrayCollection(source);
				relationsToOpen = relationList.length;
			}
		}
		
		public function getLength():int
		{
			return relationList.length;
		}
		
		public function getItemAt(index:int):Object
		{
			return relationList.getItemAt(index);
		}
		
		public function decrementRelationsToOpen():int
		{
			relationsToOpen--;
			return relationsToOpen;
		}
		
		public function wordMatched(relationSrc:TextComponent, relationDest:TextComponent):void
		{
		  	if(relationList.matchRelation(relationSrc, relationDest))
		  	{
		  		decrementRelationsToOpen();
		  		relationList.incrementKnownRelations();
		  		dispatchCorrespondingEvent();
	      	}
		}
		
		public function wordDorpped(relationSrc:TextComponent, relationDest:TextComponent):void
		{
			decrementRelationsToOpen();
		  	if(relationList.matchRelation(relationSrc, relationDest))
		  	{		  		
		  		relationList.incrementKnownRelations();		  		  		
	      	}
	      	dispatchCorrespondingEvent();	
		}
		
		private function dispatchCorrespondingEvent():void
		{
			if(relationsToOpen > 0)
		  		{
		  			dispatchEvent(new JavaFlexBoundaryConditionEvent(JavaFlexBoundaryConditionEvent.BOUNDARY_CONDITION));
		  		}
			  	else
		      	{
		      		if(relationList.getKnownRelations() == relationList.length)	      		
		      		{
		      			dispatchEvent(new JavaFlexGameOverEvent(JavaFlexGameOverEvent.WORD_GUESSED));
		      		}
		      		else
		      		{
		      			dispatchEvent(new JavaFlexGameOverEvent(JavaFlexGameOverEvent.WORD_NOT_GUESSED));
		      		}
		      	}
		}
	}
}